package com.cmcc.passenger.ui.profile


import android.Manifest
import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.core.content.FileProvider
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.cmcc.passenger.R
import com.cmcc.passenger.config.AppConfig
import com.cmcc.passenger.config.PassPath

import com.cmcc.passenger.data.entity.request.CodeRequest
import com.cmcc.passenger.data.entity.request.RegistRequest
import com.cmcc.passenger.data.entity.response.CarCategory
import com.cmcc.passenger.databinding.ActivityDriverJoinBinding
import com.cmcc.passenger.dialog.NiceDialog
import com.cmcc.passenger.ui.base.BasicActivity
import com.cmcc.passenger.ui.fragment.AppProgressDialog
import com.cmcc.passenger.ui.profile.viewmodel.ProfileViewModel
import com.cmcc.passenger.ui.utils.GetPhotoFromAlbum

import com.cmcc.shared.utils.*
import kotlinx.android.synthetic.main.activity_driver_join.*
import java.io.File

/**
 * 司机加盟
 */
@Route(path = PassPath.DRIVER_JOIN)
class
DriverJoinActivity : BasicActivity() {
    private lateinit var viewModel: ProfileViewModel
    private lateinit var binding: ActivityDriverJoinBinding

    private var progressDialog: AppProgressDialog? = null

    private var adapter: ReasonAdapter? = null

    private var categoryInfo: MutableList<CarCategory>? = ArrayList()

    /**
     * 初始化
     */
    override fun initialize(savedInstanceState: Bundle?) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_driver_join)

        progressDialog = AppProgressDialog(this)
        viewModel = ViewModelProviders.of(this).get(ProfileViewModel::class.java)


        binding.toolbar.title.text = getString(R.string.driver_join)

        binding.toolbar.toolbar.setNavigationOnClickListener { finish() }


        binding.recyclerView.layoutManager = LinearLayoutManager(this)

        val stringIntegerHashMap = HashMap<String, Int>()
        //设置下间距
        stringIntegerHashMap.put(
            RecyclerViewSpacesItemDecoration.TOP_DECORATION,
            DisplayUtil.dip2px(this, 14f)
        )
        binding.recyclerView.addItemDecoration(RecyclerViewSpacesItemDecoration(stringIntegerHashMap))


        adapter = ReasonAdapter()
        updateUI()
        binding.recyclerView.adapter = adapter

        binding.ivCoseOpen.setOnClickListener(View.OnClickListener {
            closeAnOpen();

        })


        /**
         * 获取个人信息 手机号 默认填充
         */
        viewModel.getPassengerInfo()

        /**
         * 获取车辆类别
         */
        viewModel.requestCarCategory()

        /**
         * 获取验证码
         */
        binding.tvGetCode.setOnClickListener(View.OnClickListener {
            getCode()

        })
        /**
         * 上传 图片 对话框1
         */
        binding.llUploadOne.setOnClickListener(View.OnClickListener {
            type = 1;
            showSelectPhotoTypeDialog()
            // initPermission()
        })

        binding.ivPhotoOne.setOnClickListener(View.OnClickListener {

            type = 1;
            showSelectPhotoTypeDialog()
        })
        /**
         * 上传 图片 对话框2
         */
        binding.llUploadTwo.setOnClickListener(View.OnClickListener {
            type = 2;
            showSelectPhotoTypeDialog()
            // initPermission()
        })
        binding.ivPhotoTwo.setOnClickListener(View.OnClickListener {
            type = 2;
            showSelectPhotoTypeDialog()
        })

        //协议内容
        binding.tvAgree.setOnClickListener(View.OnClickListener {
            ARouter.getInstance().build(PassPath.AGREE).navigation()

        })
        //勾选协议
        binding.ivCheck.setOnClickListener(View.OnClickListener {
            isChecked = !isChecked
            if (isChecked) {
                binding.ivCheck.setImageResource(R.drawable.image_checked)
            } else {
                binding.ivCheck.setImageResource(R.drawable.image_unchecked)
            }

        })

        //点击注册
        binding.tvRigist.setOnClickListener(View.OnClickListener {


            name = binding.etOne.text.toString()

            appellation = binding.etTwo.text.toString()

            verificationCode = binding.etFour.text.toString()

            driverCardNumber = binding.etFive.text.toString()

            driverCardTerm = binding.etSix.text.toString()

            idCard = binding.etSeven.text.toString()



            if (TextUtils.isEmpty(name)
                || TextUtils.isEmpty(appellation)
                || TextUtils.isEmpty(driverCardNumber)
                || TextUtils.isEmpty(driverCardTerm)
                || TextUtils.isEmpty(verificationCode)
                || TextUtils.isEmpty(idCard)

            ) {
                showToast(this, resources.getString(R.string.str_finish_input))
                return@OnClickListener
            }
            if (id == null) {
                showToast(this, resources.getString(R.string.str_select_car))

                return@OnClickListener

            }

            var sixs = driverCardTerm.split("-")
            if (sixs.size != 3) {
                showToast(this, resources.getString(R.string.str_date_right))

                return@OnClickListener
            }
            if (sixs[0].length != 4 || sixs[1].length != 2 || sixs[2].length != 2) {
                showToast(this, resources.getString(R.string.str_date_right))

                return@OnClickListener
            }
            if (sixs[0].toInt() < 2020) {
                showToast(this, resources.getString(R.string.str_date_right))

                return@OnClickListener
            }
            if (sixs[1].toInt() < 1 || sixs[1].toInt() > 12) {
                showToast(this, resources.getString(R.string.str_date_right))

                return@OnClickListener
            }
            if (sixs[2].toInt() < 1 || sixs[2].toInt() > 31) {
                showToast(this, resources.getString(R.string.str_date_right))

                return@OnClickListener
            }



            if (
                file1 == null
                || file2 == null
            ) {
                showToast(this, resources.getString(R.string.str_please_add))
                return@OnClickListener
            }

            if (
                (!isChecked)
            ) {
                showToast(this, resources.getString(R.string.str_please_agree))
                return@OnClickListener
            }

            progressDialog?.show()
            if (workCardFileAddress.isNullOrBlank() && driverCardFileAddress.isNullOrBlank()) {
                file1?.let { viewModel.uploadImg(1, it) }
                file2?.let { viewModel.uploadImg(2, it) }
            }else {
                regist()
            }
        })


        requestPermission();

        // model = resources.getString(R.string.str_green)


        binding.carTypeGroup.setOnCheckedChangeListener { group, checkedId ->
            categoryInfo?.forEach { carCategory ->
                if (checkedId == carCategory.customerId) {
                    // model = carCategory.name!!
                    id = carCategory.code
                }
            }

        }

    }


    override fun initObserver(savedInstanceState: Bundle?) {
        super.initObserver(savedInstanceState)

        viewModel.upload.observe(this, Observer { uploadInfo ->
            if (uploadInfo.code == 200) {
                Log.e(TAG, "文件地址:$uploadInfo")
                //从业资格证文件地址
                workCardFileAddress = uploadInfo.data
            } else {
                showToast(this, uploadInfo.msg)
            }
        })

        viewModel.upload2.observe(this, Observer { uploadInfo ->
            if (uploadInfo.code == 200) {
                Log.e(TAG, "文件地址:$uploadInfo")
                //驾驶证
                driverCardFileAddress = uploadInfo.data
            } else {
                showToast(this, uploadInfo.msg)
            }
        })

        viewModel.addAllUploadMsg()

        viewModel.uploadCompleteMsg.observe(this, Observer {
            progressDialog!!.dismiss()
            if (it) {
                //注册
                regist()
            }
        })

        /**
         * 注册 回调
         */
        viewModel.regist.observe(this, Observer { regist ->
            progressDialog!!.dismiss()
            if (regist.code == 200) {
                //注册成功
//                reviewStatusIng()
                showToast(this, getString(R.string.submit_success))
                finish()
            } else {
                showToast(this, regist.msg)
            }


        })
        /**
         * 获取个人信息回调
         */
        viewModel?.passengerInfo?.observe(this, Observer { info ->
            binding.etThree.text = info.phone
            headPortraitAddress = info.headPortraitAddress

        })

        /**
         * 获取验证码回调
         */
        viewModel?.code?.observe(this, Observer { code ->
            progressDialog?.dismiss()
            if (code.code == 200) {
                verificationCodeId = code.data
                // verificationCodeId = "000000"
                Log.e(TAG, code.data)
//                showToast(this,resources.getString(R.string.get_code_success))
                binding.tvGetCode.isEnabled = false
                binding.tvGetCode.text = (time.toString() + "s")
                RxTimerUtil.interval(1000, object : RxTimerUtil.IRxNext {
                    override fun doNext() {
                        if (time == 1) {
                            binding.tvGetCode.text = resources.getString(R.string.str_get)
                            binding.tvGetCode.isEnabled = true
                            RxTimerUtil.cancel()
                            time = 60
                        } else {
                            time--
                            binding.tvGetCode.text = time.toString() + "s"

                        }
                    }
                })

            } else {
                showToast(this, code.msg)
            }


        })

        /**
         * 车辆类别回调
         */
        viewModel?.carCategory?.observe(this, Observer { carCategory ->
            progressDialog?.dismiss()
            if (carCategory.isNotEmpty()) {
                categoryInfo?.clear()
                categoryInfo?.addAll(carCategory)
                addRadioButton(binding.carTypeGroup)

            }


        })

    }

    private var time = 60

    /**
     * 获取验证码
     */
    private fun getCode() {
        progressDialog?.show()
        viewModel.code(CodeRequest(binding.etThree.text.toString()))

    }

    /**
     * 添加radiobutton
     */
    private fun addRadioButton(radioGroup: RadioGroup) {


        for (index in 0..categoryInfo!!.size - 1) {
            categoryInfo!!.get(index).customerId = index

            val radioButton = RadioButton(this)
            setRadioAttribute(
                radioButton,
                categoryInfo!!.get(index).name!!,
                categoryInfo!!.get(index).customerId
            )

            radioGroup.addView(radioButton)
        }

    }


    private fun setRadioAttribute(radioButton: RadioButton, name: String, customerId: Int) {
        radioButton.setPaddingRelative(0, 0, 12, 0)

        radioButton.textSize = 18f
        radioButton.id = customerId
        radioButton.text = name

        if (Build.VERSION.SDK_INT >= 23) {
            val colorStateList =
                this.resources.getColorStateList(R.color.driver_signin_btn_green, null)
            radioButton.buttonTintList = colorStateList

        }

    }

    /**
     * 审核ing
     */
    private fun reviewStatusIng() {
        var dialog: Dialog =
            PassDialogUtils.getDialog(
                this,
                R.layout.dialog_regis_ing
            )
        dialog.show()
        dialog.setOnDismissListener(DialogInterface.OnDismissListener {
            finish()

        })
    }


    /**
     * 提示
     */
    private fun revieTips() {
        var dialog: Dialog =
            PassDialogUtils.getDialogNotTouchOutside(
                this,
                R.layout.dialog_regis_tips
            )
        dialog.show()
        dialog.findViewById<View>(R.id.tv_ok).setOnClickListener(View.OnClickListener {
            dialog.dismiss()
            closeAnOpen()
        })

    }


    private var name = ""//": "",                 //司机昵称
    private var appellation = ""//": "",          //称呼
    private var headPortraitAddress = ""//": "",  //头像
    private var driverCardNumber = ""//": "",     //驾驶证号码
    private var driverCardTerm = ""//": "",       //有效期
    private var driverCardFileAddress = ""//": "",//驾驶证文件地址
    private var workCardNumber = ""//": "",       //从业资格证号码
    private var workCardFileAddress = ""//": "",  //从业资格证文件地址
    private var verificationCodeId = ""//": "",       //验证码ID
    private var verificationCode = ""//": "",  //验证码


    //DriverCar
    private lateinit var idCard: String//": "",                 //车牌号
    // private lateinit var model: String

    //CarCategory
    private var id: String? = null//": "",                 //车辆类别ID

    private var isChecked = false

    /**
     * 注册
     */
    private fun regist() {

        progressDialog?.show()
        var request: RegistRequest = RegistRequest(
            name,
            appellation,
            headPortraitAddress,
            driverCardNumber,
            driverCardTerm,
            AppConfig.FILE_URL + driverCardFileAddress, workCardNumber,
            AppConfig.FILE_URL + workCardFileAddress,
            verificationCodeId,
            verificationCode,
            idCard,
            "",
            id ?: ""
        )
        viewModel.register(request)

    }

    /**
     * 动态请求定位权限
     */
    private fun requestPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return
        }

        requestPermissions(
            arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            ), 3
        )

    }


    private var isOpen: Boolean = false;

    private var file1: File? = null
    private var file2: File? = null

    lateinit var cameraSavePath: File
    lateinit var uri: Uri
    var type: Int = 0

    /**
     * 打开按钮 是否为康泰司机
     */
    private fun closeAnOpen() {

        //当前为打开 就去关闭
        if (isOpen) {
            binding.tvRigist.isEnabled = true
            iv_cose_open.setImageResource(R.drawable.ic_close_pass)
            binding.rlOne.visibility = View.VISIBLE
            binding.rlTwo.visibility = View.VISIBLE
            binding.rlThree.visibility = View.VISIBLE
            binding.rlFour.visibility = View.VISIBLE
            binding.rlFive.visibility = View.VISIBLE
            binding.rlSix.visibility = View.VISIBLE
            binding.rlSeven.visibility = View.VISIBLE
            binding.rlEight.visibility = View.VISIBLE
            binding.rlNine.visibility = View.VISIBLE
            binding.rlTen.visibility = View.VISIBLE

        }
        // 去打开
        else {
            binding.tvRigist.isEnabled = false
            revieTips();
            iv_cose_open.setImageResource(R.drawable.ic_open_pass)
            binding.rlOne.visibility = View.GONE
            binding.rlTwo.visibility = View.VISIBLE
            binding.rlThree.visibility = View.VISIBLE
            binding.rlFour.visibility = View.GONE
            binding.rlFive.visibility = View.GONE
            binding.rlSix.visibility = View.GONE
            binding.rlSeven.visibility = View.GONE
            binding.rlEight.visibility = View.GONE
            binding.rlNine.visibility = View.GONE
            binding.rlTen.visibility = View.GONE
        }

        isOpen = !isOpen;
    }

    private fun updateUI() {
        //拍照的文件存储位置
        cameraSavePath =
            File(Environment.getExternalStorageDirectory().path + "/" + System.currentTimeMillis() + ".jpg")
    }


    /**
     * 选中照片
     */
    private fun showSelectPhotoTypeDialog() {
        NiceDialog.init()
            .setLayoutId(R.layout.dialog_photo_select)
            .setConvertListener { holder, dialog ->
                dialog.setOutCancel(false)
                val btnTakingPictures =
                    holder.getView(R.id.btn_taking_pictures) as Button
                val btnPhotoAlbum =
                    holder.getView(R.id.btn_photo_album) as Button
                val btnCancel =
                    holder.getView(R.id.btn_cancel) as Button
                btnCancel.setOnClickListener { dialog.dismiss() }
                //拍照
                btnTakingPictures.setOnClickListener {
                    dialog.dismiss()
                    goCamera()
                }
                //相册
                btnPhotoAlbum.setOnClickListener {
                    dialog.dismiss()
                    goAlbum()
                    //
                }
            }
            .setShowBottom(true)
            .show(supportFragmentManager)

    }


    //设置权限请求和活动请求的请求码requestCode
    companion object {

        private const val ACTIVITY_REQUEST_ALBUM = 3
        private const val ACTIVITY_REQUEST_CAMERA = 4
    }


    //相册功能
    private fun goAlbum() {
        val intent = Intent()
        intent.action = Intent.ACTION_PICK
        intent.type = "image/*"
        startActivityForResult(intent, ACTIVITY_REQUEST_ALBUM)
    }

    //拍照功能
    private fun goCamera() {

        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri =
                FileProvider.getUriForFile(
                    this,
//                    "com.ChinaMobile.push.fileProvider",
                    "com.chinamobile.push.fileProvider",
                    cameraSavePath
                )
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        } else {
            uri = Uri.fromFile(cameraSavePath)
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        this.startActivityForResult(intent, ACTIVITY_REQUEST_CAMERA)
    }

    //活动请求的回调，用requestCode来匹配
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        //图片路径
        var photoPath: String = ""

        //相册
        if (requestCode == ACTIVITY_REQUEST_ALBUM && resultCode == Activity.RESULT_OK) {

            photoPath = data!!.data?.let { GetPhotoFromAlbum.getRealPathFromUri(this, it) }!!
            Log.e(TAG, photoPath)

            if (type == 1) {
                file1 = File(photoPath)
                binding.llUploadOne.visibility = View.GONE
                binding.ivPhotoOne.visibility = View.VISIBLE
                Glide.with(this)
                    .load(photoPath)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivPhotoOne)
            }
            if (type == 2) {
                file2 = File(photoPath)
                binding.llUploadTwo.visibility = View.GONE
                binding.ivPhotoTwo.visibility = View.VISIBLE
                Glide.with(this)
                    .load(photoPath)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivPhotoTwo)
            }


            //拍照
        } else if (requestCode == ACTIVITY_REQUEST_CAMERA && resultCode == Activity.RESULT_OK) {

            photoPath = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                cameraSavePath.toString()
            } else {
                uri.encodedPath!!
            }


            if (type == 1) {
                file1 = File(photoPath)
                binding.llUploadOne.visibility = View.GONE
                binding.ivPhotoOne.visibility = View.VISIBLE
                Glide.with(this)
                    .load(photoPath)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivPhotoOne)
            }
            if (type == 2) {
                file2 = File(photoPath)
                binding.llUploadTwo.visibility = View.GONE
                binding.ivPhotoTwo.visibility = View.VISIBLE
                Glide.with(this)
                    .load(photoPath)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivPhotoTwo)
            }


        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    fun RequestOptions.miniThumb(size: Int): RequestOptions {
        return this.fitCenter()
            .override(100)
    }

}
